<template>
  <div class="app-container">

    <el-card class="box-card d1">
      <p style="font-size: 14px"><a @click="back"><i class="el-icon-back" style="width: 20px"></i>返回</a></p>
      <h4><i class="el-icon-paperclip"></i> 基本信息</h4>
      <el-row>
        <el-col :span="24">
          <el-form label-position="labelPosition"  ref="formPatient" :model="formPatient" :rules="rulesPatient" label-width="80px"  >
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名" prop="patientName">
                  <el-input v-model="formPatient.patientName" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="formPatient.idCard" placeholder="请输入身份证号" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="formPatient.gender" placeholder="请选择性别" clearable>
                    <el-option
                      v-for="dict in dict.type.his_doctor_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model="formPatient.age" placeholder="请输入患者年龄" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="电话/手机" prop="tel">
                  <el-input v-model="formPatient.tel" placeholder="请输入患者电话" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="报告编号" prop="outpatient">
                  <el-input v-model="formPatient.sliceNo" placeholder="请输入报告编号" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="是否初筛" prop="screen">
                  <el-select v-model="formPatient.screen" placeholder="请选择是否初筛" clearable>
                    <el-option
                      v-for="dict in dict.type.his_screen"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="体重" prop="screen">
                  <el-tooltip class="item" effect="light" content="单位：kg" placement="right">
                   <el-input v-model="formPatient.weight" placeholder="请输入体重" />
                  </el-tooltip>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="评估机构" prop="unit">
                    <el-input v-model="formPatient.unit" placeholder="请输入评估机构" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="是否转院" prop="director">
                  <el-select v-model="formPatient.director" placeholder="请选则是否转院" clearable>
                    <el-option
                      v-for="dict in dict.type.his_director"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="药物史" prop="drugs">
                  <el-input v-model="formPatient.drugs" placeholder="请输入药物史" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="过往病史" prop="drugs">
                  <el-input v-model="formPatient.allergy" placeholder="过往病史" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="常住地址" prop="address">
                  <el-input v-model="formPatient.address" placeholder="请输入常住地址" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="筛查结果" prop="status">
                  <el-select v-model="formPatient.status" placeholder="请选择筛查结果" clearable>
                    <el-option
                      v-for="dict in dict.type.his_screening_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formPatient.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <div class="op-container" style="float: right">
                <el-button @click="handleCancel">返回</el-button>
                <el-button type="primary" :loading="btnLoading" @click="submitForm">更新</el-button>
              </div>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card d3" v-if="visbleJsz">
      <h4><i class="el-icon-finished"></i> 老年衰弱/肌少症风险评估及建议</h4>
      <el-button :plain="true" type="primary" size="mini" @click="handlePatientResult({subscreening:queryLnParams.subscreening},1)">添加</el-button>
      <el-table :data="screeningLn">
        <el-table-column property="screeningItem" label="筛查项目"/>
        <el-table-column property="screeningResult" label="筛查结果"/>
        <el-table-column property="referenceRange" label="参考范围"/>
        <el-table-column property="riskWarning" label="风险提示"/>
        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button :plain="true" type="primary" size="mini" @click="handlePatientResult(scope.row,1)">设置</el-button>
            <el-button :plain="true" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="left">结论及建议</el-divider>
      <el-row style="margin-top: 20px" class="text_area">
        <el-col :span="24">
          <el-form label-position="labelPosition" ref="formAdvise" :model="formAdvise" :rules="rulesAdvise" label-width="80px"  >
            <el-row>
              <el-col :span="12">
                <el-form-item label="" prop="lnAdvise">
                  <el-input type="textarea" v-model="formAdvise.lnAdvise" placeholder="" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card d4" v-if="visbleKspg">
      <h4><i class="el-icon-finished"></i> 快速综合评估结果</h4>
<!--      <el-button :plain="true" type="primary" size="mini" @click="handlePatientResult({subscreening: queryKsParams.subscreening},2)">添加</el-button>-->
      <el-row>
        <div class="op-container" style="float: right;margin-bottom: 10px">
          <el-button :plain="true" type="primary" size="mini" @click="loadPdf">报告预览</el-button>
        </div>
      </el-row>

      <el-table :data="screeningKs">
        <el-table-column property="screeningItem" label="筛查项目"/>
        <el-table-column property="screeningResult" label="筛查结果"/>
        <el-table-column property="referenceRange" label="参考范围" width="360"/>
        <el-table-column property="riskWarning" label="风险提示"/>
        <el-table-column property="advise" label="结论建议"/>
        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button :plain="true" type="primary" size="mini" @click="handlePatientResult(scope.row,2)">设置</el-button>
            <el-button :plain="true" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="left">结论及建议</el-divider>
      <el-row style="margin-top: 20px" class="text_area">
        <el-col :span="24">
          <el-form label-position="labelPosition" ref="formAdvise" :model="formAdvise" :rules="rulesAdvise" label-width="80px"  >
            <el-row>
              <el-col :span="12">
                <el-form-item label="" prop="ksAdvise">
                  <el-input type="textarea" v-model="formAdvise.ksAdvise" placeholder="" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog :visible.sync="resultVisiable" width="560px" title="风险计算结果">
      <el-form ref="formResult" :model="formResult" :rules="rulesResult" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:20px;">
        <el-form-item label="筛查项目" prop="screeningItem">

          <el-select v-model="formResult.screeningItem" placeholder="请选择筛查项目" clearable>
            <div v-if="this.dicts_state==2">
              <el-option
                v-for="dict in dict.type.his_screening_item"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </div>
            <div v-if="this.dicts_state==1">
              <el-option
                v-for="dict in dict.type.his_saas_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </div>
          </el-select>
        </el-form-item>
        <el-form-item label="筛查结果" prop="screeningResult">
          <el-input v-model="formResult.screeningResult"/>
        </el-form-item>
        <el-form-item label="参考范围" prop="referenceRange">
          <el-input v-model="formResult.referenceRange"/>
        </el-form-item>
        <el-form-item label="风险提示" prop="riskWarning">
          <el-select v-model="formResult.riskWarning" placeholder="请选择风险类型" clearable>
            <el-option
              v-for="dict in dict.type.his_risk_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resultVisiable = false">取消</el-button>
        <el-button type="primary" @click="handleResultEdit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&patientId=' + upload.patientId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            <el-input v-model="upload.patientId" type="hidden" ></el-input>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <div class="op-container">
      <el-button @click="handleCancel">返回</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitForm">更新</el-button>
    </div>

  </div>
</template>

<style>
.fixed-width .el-button--mini {
  width: 60px !important;
}
.d1 .el-input {
  width: 79%;
}
.d1 .el-textarea__inner{
  width: 79% ;
}
.d1 .el-form-item__label {
  width: 102px !important;
}
.d1 .el-form-item__content{
  margin-left: 102px !important;
}

.d2 .el-input {
  width: 100%;
}
.d2 .el-textarea__inner{
  width: 100% ;
}
.d2 .el-form-item__label {
  width: 126px !important;
}
.d2 .el-form-item__content{
  margin-left: 126px !important;
}
.d2 .el-input__inner{
  padding: 0 8px !important;
}
.d2 .date_pick .el-input__inner{
  padding-left: 36px !important;
}
.d2 .el-card__body {
  padding-bottom: 10px !important;
}
.d3 .text_area .el-form-item__content{
  margin-left: 0 !important;
}
/*.d3 .el-textarea__inner{
  height: 76px !important;
}*/

.d4 .el-form-item {
  margin-bottom: 10px !important;
}
/*.d4 .el-textarea__inner{
  height: 96px !important;
}*/
.d4 .el-form-item__content{
  margin-left: 0 !important;
}

.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.d1 .el-card__body {
  padding: 0 20px 20px 20px !important;
}
</style>

<script>

import { updatePatient, getPatient, addPatient } from '@/api/his/patient'
import { updateAttribute, getAttribute, addAttribute } from '@/api/his/attribute'
import { addScreening, listScreening, updateScreening, delScreening} from '@/api/his/screening'
import { getToken } from "@/utils/auth";
import { tansParams } from '@/utils/ruoyi'
import axios from 'axios'

export default  {
  name: 'KspgEdit',
  dicts: [
    'his_doctor_sex',
    'his_screening_item',
    'his_saas_type',
    'his_risk_type',
    'his_marital_type',
    'his_degree',
    'his_income',
    'his_living',
    'his_caregiver',
    'his_director',
    'his_screen',
    'his_risk_calculation_model',
    'his_screening_status'
  ],
  data() {
    return {
      dicts_state:1,
      visbleJsz: false,
      visbleKspg: false,
      // 表单参数
      formPatient: {},
      formAttribute:{
        patientId:0,
        alb:'',
        ast:'',
        rsp:'',
        kdp:'',
        vd:'',
        cre:'',
        fa:'',
        rbc:'',
        fpg:'',
        hgb:'',
        mcv:'',
        acp:'',
        p:'',
        k:'',
        tp:'',
        na:'',
        il:'',
        trh:'',
        ft4:'',
        cc:'',
        mda:'',
        b12:'',
        wbc:'',
        plt:'',
        tag:'',
        alt:'',
        ldl:'',
      },
      formResult:{},
      formAdvise:{},
      formRisk:{},
      // 表单校验
      rulesPatient: {
        patientName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
         gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        unit: [
          { required: false, message: "采血单位不能为空", trigger: "blur" }
        ],
        slice_no: [
          { required: true, message: "报告编号不能为空", trigger: "blur" }
        ],
        ctime: [
          { required: false, message: "采血日期不能为空", trigger: "blur" }
        ],
        weight: [
          { required: true, message: "体重不能为空", trigger: "blur" }
        ],
        marital: [
          { required: false, message: "婚姻状况不能为空", trigger: "blur" }
        ],
        degree: [
          { required: false, message: "文化程度不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "电话手机号不能为空", trigger: "blur" }
        ],
        collector: [
          { required: false, message: "采血人不能为空", trigger: "blur" }
        ],
        inputby: [
          { required: false, message: "信息录入者不能为空", trigger: "blur" }
        ],
        reviewer: [
          { required: false, message: "审核者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: false, message: "录入时间不能为空", trigger: "blur" }
        ],
      },
      rulesAttribute:{},
      rulesResult:{
        screeningItem:[
          {required: true, message: "请选择筛查项目", trigger: "blur" }
        ],
        screeningResult:[
          {required: true, message: "筛查结果不能为空", trigger: "blur" }
        ],
        referenceRange:[
          {required: true, message: "参考范围不能为空", trigger: "blur" }
        ],
        riskWarning:[
          {required: true, message: "请选择风险类型", trigger: "blur" }
        ]
      },
      rulesAdvise:{},
      rulesRisk:{
        collector: [
          { required: false, message: "采血人不能为空", trigger: "blur" }
        ],
        inputby: [
          { required: false, message: "信息录入者不能为空", trigger: "blur" }
        ],
        reviewer: [
          { required: false, message: "审核人不能为空", trigger: "blur" }
        ],
        inspector: [
          { required: false, message: "检验人不能为空", trigger: "blur" }
        ],
      },
      btnLoading: false,
      isExit: false,
      resultVisiable: false,
      screeningLn: [],
      screeningKs: [],
      queryLnParams: {
        patientId: 0,
        subscreening:'实验室老年衰弱/肌少症筛查'
      },
      queryKsParams: {
        patientId: 0,
        subscreening:'快速综合评估'
      },

      // 导入指标参数
      upload: {
        patientId: 0,
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        //url: process.env.VUE_APP_BASE_API + "/his/attribute/importData"
        url: process.env.VUE_APP_BASE_API + "/his/attribute/batchImportData"
      },
    }
  },

  created() {
    this.init()
  },

  methods: {
    async loadPdf() {
      const loading = this.$loading({
        //lock: true,
        text: '报告生成中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
      });

      const baseURL = process.env.VUE_APP_BASE_API;
      const api ='/his/patient/zhpgReport';
      var query = {patient: JSON.stringify(this.formPatient) ,screening: JSON.stringify(this.screeningKs)};
      var url = baseURL + api + '?' + tansParams(query);
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        params: {},
        headers: { Authorization: "Bearer " + getToken() },
      }).then(res =>{
          loading.close();
          const blob = new Blob([res.data], {type: 'application/pdf'})
          let href = URL.createObjectURL(blob)
          window.open(href)
        }
      )
    },

    init(row) {
      //const patient_id = this.$route.query.id
      const id = this.queryLnParams.patientId = this.queryKsParams.patientId = this.upload.patientId = this.$route.params && this.$route.params.id;

      getPatient(id).then(response => {
        this.formPatient = this.formRisk = this.formAdvise = response.data;
        //获取筛查参数指标
        getAttribute(id).then(response => {
          if(response.data != undefined){
            this.formAttribute = response.data;
            this.isExit = true;
          }else{
            this.formAttribute.patientId = id;
          }
        });

        //获取筛查结果
        listScreening(this.queryLnParams).then(response => {
          this.screeningLn = response.rows;
        });
        listScreening(this.queryKsParams).then(response => {
          this.screeningKs = response.rows;
        });

        if(response.data.subscreening == '实验室老年衰弱/肌少症'){
          this.visbleJsz = true;
        }else if(response.data.subscreening == '快速综合评估'){
          this.visbleKspg = true;
        }
      });


    },
    /** 提交按钮 */
    submitForm() {
      this.btnLoading = true;
      let formPatient=new Promise((resolve,reject)=>{
        this.$refs["formPatient"].validate((valid)=>{
          if(valid){
            resolve();
          }else{
            this.btnLoading = false;
            return false;
          }

        });
      });
      /* let formAttribute=new Promise((resolve,reject)=>{
        this.$refs["formAttribute"].validate((valid)=>{
          if(valid){
            resolve();
          }else{
            this.btnLoading = false;
            return false;
          }
        });
      }); */
      /* let formRisk=new Promise((resolve,reject)=>{
        this.$refs["formRisk"].validate((valid)=>{
          if(valid){
            resolve();
          }else{
            this.btnLoading = false;
            return false;
          }
        });
      }); */

      Promise.all([formPatient]).then(()=>{
        //更新患者基本信息
        if (this.formPatient.id != null) {
          this.formPatient.remark = this.formAdvise.remark;
          this.formPatient.riskModel = this.formRisk.riskModel;
          this.formPatient.collector = this.formRisk.collector;
          this.formPatient.reviewer = this.formRisk.reviewer;
          this.formPatient.createBy = this.formRisk.createBy;
          this.formPatient.ctime = this.formRisk.ctime;
          updatePatient(this.formPatient).then(response => {
            //this.$router.push({ path: '/reg_treat/patient'})
          });
        } else {
          addPatient(this.formPatient).then(response => {
            //this.$router.push({ path: '/reg_treat/patient' })
          });
        }

        //更新患者疾病指标
        if (this.isExit) {
          updateAttribute(this.formAttribute).then(response => {
            //this.$router.push({ path: '/reg_treat/patient'})
          });
        } else {
          addAttribute(this.formAttribute).then(response => {
            //this.$router.push({ path: '/reg_treat/patient' })
          });
        }

        this.$modal.msgSuccess("更新成功");
        this.$router.push({ path: '/kszh/kspg'})
      })

    },

    handlePatientResult(row,type) {
      this.dicts_state = type
      this.formResult = Object.assign({}, row)
      this.resultVisiable = true
    },

    handleDelete(row){
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除"' + row.screeningItem + '"的数据项？').then(function() {
        //return delScreening(id);
      }).then(() => {
        this.init();
        this.$modal.msgSuccess("暂无法删除");
        //this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

    },

    handleResultEdit() {
      this.$refs["formResult"].validate(valid => {
        if (valid) {
          this.formResult.addTime = Date.now();
          if (this.formResult.sid != null) {
            updateScreening(this.formResult).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resultVisiable = false;
              this.init();
            });
          } else {
            this.formResult.patientId = this.queryKsParams.patientId = this.queryLnParams.patientId;
            addScreening(this.formResult).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resultVisiable = false;
              this.init();
            });
          }
        }
      });
    },

    handleCancel: function() {
      this.$router.push({ path: '/kszh/kspg'})
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "筛查结果导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('his/attribute/importTemplate', {
      }, `attribute_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.init();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    back(){
      this.$router.push({path:'/kszh/kspg'})
    },
  }
}
</script>
